package udp_tcp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) {
        // 服务器地址和端口
        String serverHost = "localhost";
        int serverPort = 9876;

        try (DatagramSocket clientSocket = new DatagramSocket();
             Scanner scanner = new Scanner(System.in)) {

            InetAddress serverAddress = InetAddress.getByName(serverHost);

            while (true) {
                System.out.print("请输入要发送的消息(输入exit退出): ");
                String message = scanner.nextLine();

                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }

                // 准备发送数据
                byte[] sendData = message.getBytes();

                // 创建并发送数据包
                DatagramPacket sendPacket = new DatagramPacket(
                        sendData,
                        sendData.length,
                        serverAddress,
                        serverPort
                );
                clientSocket.send(sendPacket);

                // 创建接收数据的缓冲区
                byte[] receiveData = new byte[1024];

                // 创建接收数据包
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收响应
                clientSocket.receive(receivePacket);

                // 解析响应数据
                String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("服务器响应: " + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}